package com.crealth.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import com.alibaba.fastjson.JSONObject;



public class Utils {
	private static Logger errorLog = Logger.getLogger("error_log");
	
	public static String getOSName() {
		Properties props=System.getProperties();
		String osName = props.getProperty("os.name");
		return osName;
	}
	
	public static boolean isWindows() {
		String osName = Utils.getOSName();
		if (osName.startsWith("Window")) {
			return true;
		}
		
		return false;
	}
	
	public static void checkAndCreateDir(String fileDir) {
		File file = new File(fileDir);
		//如果文件夹不存在则创建    
		if (!file .exists() && !file.isDirectory())      
		{
		    file.mkdir();    
		}
	}
	
	public static long getCurrentWeekStartTm() {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
		if (dayOfWeek == Calendar.SUNDAY) {
			int weekOfMonth = cal.get(Calendar.WEEK_OF_MONTH);
			cal.set(Calendar.WEEK_OF_MONTH, weekOfMonth-1);
		}
		cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		
		return cal.getTimeInMillis();
	}
	
	public static long getCurrentMonthStartTm() {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.DAY_OF_MONTH, 1);
		
		return cal.getTimeInMillis();
	}
	
	public static Timestamp getCurrentMonthStartTimestamp() {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.DAY_OF_MONTH, 1);
		
		long tm = cal.getTimeInMillis();
		Timestamp timestp = new Timestamp(tm);
		
		return timestp;
	}
	
	public static Timestamp getTodayTimestamp() {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		Timestamp tm = new Timestamp(cal.getTimeInMillis());
		
		return tm;
	}
	
	public static String getJsonString(JSONObject json, String key) {
		if (json.containsKey(key)) {
			return json.getString(key);
		}
		
		return "";
	}
	
	public static int getJsonIntValue(JSONObject json, String key, int defValue) {
		if (json.containsKey(key)) {
			return json.getIntValue(key);
		}
		
		return defValue;
	}
	
	public static String getCurrentYearMonth() {
		String returnStr = null;  
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM");  
        Date date = new Date();  
        returnStr = f.format(date);  
        return returnStr;
	}
	
	public static String getCurrentYearMonth2() {
		String returnStr = null;  
        SimpleDateFormat f = new SimpleDateFormat("yyyyMM");  
        Date date = new Date();  
        returnStr = f.format(date);  
        return returnStr;
	}
	
	public static String getYearMonth(long tm) {
		String returnStr = null;  
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM");
        Date date = new Date();
        date.setTime(tm);
        returnStr = f.format(date);
        
        return returnStr;
	}
	
	public static String getYearMonthDay(long tm) {
		String returnStr = null;  
        SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date();
        date.setTime(tm);
        returnStr = f.format(date);
        
        return returnStr;
	}
	
	public static String getDbYearMonthDay(Timestamp tm) {
		String returnStr = null;  
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        date.setTime(tm.getTime());
        returnStr = f.format(date);
        
        return returnStr;
	}
	
	public static Timestamp getTmFromString(String strMonth) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
		Date date = null;
		Timestamp tm = null;
		try {
			date = format.parse(strMonth);
			tm = new Timestamp(date.getTime());
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return tm;
	}
	
	public static Timestamp getTmFromYYYYMMDDString(String strMonth) {
		 SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		   Date date = null;
		   Timestamp tm = null;
		   try {
			   date = format.parse(strMonth);
			   tm = new Timestamp(date.getTime());
		   } catch (ParseException e) {
			   e.printStackTrace();
		   }
		   return tm;
	}
	
	public static Timestamp getMonthEndTm(Timestamp monthTm) {
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(monthTm.getTime());
		cal.set(Calendar.MONTH, cal.get(Calendar.MONTH)+1);
		
		long tm = cal.getTimeInMillis();
		Timestamp tmObj = new Timestamp(tm);
		return tmObj;
	}
	
	public static Timestamp getWeekEndTm(Timestamp weekStartTm) {
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(weekStartTm.getTime());
		cal.set(Calendar.WEEK_OF_MONTH, cal.get(Calendar.WEEK_OF_MONTH)+1);
		
		long tm = cal.getTimeInMillis();
		Timestamp tmObj = new Timestamp(tm);
		return tmObj;
	}	
	
	public static boolean deleteFile(String fileName) {
		File file = new File(fileName);
		if (file.exists() && file.isFile()) {
			return file.delete();
		}
		
		return false;
	}
	
	//  获取文件后缀  jpg  rar  
	public static String getFileSuffix(String fileName) {
		String suffix = "";
		if (fileName == null || fileName.length() < 2) {
			return suffix;
		}
		int spaceIdx = fileName.lastIndexOf(".");
		if (spaceIdx > 0) {
			suffix = fileName.substring(spaceIdx+1);
			suffix = suffix.toLowerCase();
		}
		
		return suffix;
	}
	
	// 
	public static Date getPreMonthDate(Date baseData, int preMonth) {
		Calendar cal = Calendar.getInstance();
	    cal.setTime(baseData);
	    cal.add(Calendar.MONTH, preMonth);
	    Date preMonthDate = cal.getTime();
	    
	    return preMonthDate;
	}
	
	//  接收文件
	public static boolean saveUploadFile(int userID, String dataType, String data, 
			String srcFileName,
			String desFileName, String desDir ) {
		byte[] resBytes;
		try {
			resBytes = Base64.decodeBase64(data);						
		} catch (Exception ex) {
			errorLog.error("write file", ex);
			return false;
		}
		
		Utils.checkAndCreateDir(desDir);
		String osName = Utils.getOSName();
		if (osName.startsWith("Window")) {
		}
		else {
			File f = new File(desDir);
	        f.setWritable(true, false);
		}
		String wFileName;
		if (desDir.endsWith("/")) {
			wFileName = desDir + desFileName;
		} else {
			wFileName = desDir + "/" + desFileName;
		}
		
		try {
			FileOutputStream fos = new FileOutputStream(wFileName);
			fos.write(resBytes);
			fos.flush();
			fos.close();
		} catch (IOException e) {
			errorLog.error("write file", e);
			return false;
		}
		
		return true;
	}
	
	public static boolean compareVersion(String minVersion, String cliVersion)
	{
		String minV[] = minVersion.split("\\.");
		String cliV[] = cliVersion.split("\\.");
		int min1 = Integer.valueOf(minV[0]);
		int min2 = Integer.valueOf(minV[1]);
		int min3 = Integer.valueOf(minV[2]);
		int cli1 = Integer.valueOf(cliV[0]);
		int cli2 = Integer.valueOf(cliV[1]);
		int cli3 = Integer.valueOf(cliV[2]);
		if (cli1 > min1) {
			return true;
		}
		if (cli1 == min1 && cli2 > min2) {
			return true;
		}
		if (cli1 == min1 && cli2 == min2 && cli3 >= min3) {
			return true;
		}
		
		return false;
	}
	
	
}
